package com.free.mini.gateway.utils.encryption;

import java.security.Key;

import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import javax.crypto.spec.IvParameterSpec;

import cn.hutool.core.codec.Base64;

public class DESUtil {
    
    private final static String secretKey = "7c18dcbb352333fe408d998b2f87dc141d4849bc";
    private final static String iv = "opay1";
    private final static String encoding = "utf-8";
    
    /**
     * 加密
     *
     * @param plainText
     * @return
     */
    public static String encodeFunction(String plainText) {
        try {
            Key deskey;
            DESedeKeySpec spec = new DESedeKeySpec(secretKey.getBytes());
            SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("desede");
            deskey = keyfactory.generateSecret(spec);
            Cipher cipher = Cipher.getInstance("desede/CBC/PKCS5Padding");
            IvParameterSpec ips = new IvParameterSpec(iv.getBytes());
            cipher.init(Cipher.ENCRYPT_MODE, deskey, ips);
            byte[] encryptData = cipher.doFinal(plainText.getBytes(encoding));
            return Base64.encode(encryptData) + plainText.substring(15, 19);
        } catch (Exception e) {
            throw new RuntimeException("加密错误!", e);
        }
    }
    
    /**
     * 解密
     * @param encryptText
     * @return
     */
    public static String decodeFunction(String encryptText) {
        try {
            encryptText = encryptText.substring(0, encryptText.length() - 4);
            DESedeKeySpec spec = new DESedeKeySpec(secretKey.getBytes());
            SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("desede");
            Key deskey = keyfactory.generateSecret(spec);
            Cipher cipher = Cipher.getInstance("desede/CBC/PKCS5Padding");
            IvParameterSpec ips = new IvParameterSpec(iv.getBytes());
            cipher.init(Cipher.DECRYPT_MODE, deskey, ips);
            byte[] decryptData = cipher.doFinal(Base64.decode(encryptText));
            return new String(decryptData, encoding);
        } catch (Exception e) {
            throw new RuntimeException("解密错误!", e);
        }
    }
}
